package com.finger.forest;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.finger.forest.base.BaseActivity;
import com.finger.forest.base.BaseView;
import com.finger.forest.base.CommonKey;
import com.finger.forest.base.ResponseTag;
import com.finger.forest.http.presenter.RegisterPresenter;
import com.finger.forest.model.CollectionRoadModel;
import com.finger.forest.utils.AndroidUtil;
import com.finger.forest.utils.ClickUtils;
import com.finger.forest.utils.DateUtil;
import com.finger.forest.utils.StringUtil;
import com.finger.forest.utils.ToastUtils;
import com.finger.forest.utils.Utils;
import com.finger.forest.utils.encode.PrefsUtil;
import com.jakewharton.rxbinding2.view.RxView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 道路采集信息
 */
public class CollectionRoadOthersActivity extends BaseActivity<RegisterPresenter> implements BaseView {

    private static final String TAG = "CollectionRoadOthersAct";

    /**
     * 返回
     */
    @BindView(R.id.btn_back)
    ImageView backIv;
    @BindView(R.id.bnSave)
    Button bnSave;
    @BindView(R.id.etRoadName)
    EditText etRoadName;

    @BindView(R.id.tvRoadType)
    TextView tvRoadType;
    @BindView(R.id.tvCreateTime)
    TextView createTimeTv;
    @BindView(R.id.tvRoadLeave)
    TextView tvRoadLeave;
    @BindView(R.id.etRemark)
    EditText etRemark;

    @BindView(R.id.llRoadLeave)
    LinearLayout llRoadLeave;
    @BindView(R.id.llRoadType)
    LinearLayout llRoadType;
    @BindView(R.id.llContent)
    LinearLayout llContent;

    /**
     * 列表
     */
    @BindView(R.id.btn_right)
    ImageView rightIv;

    private List<String> mTypeItems = new ArrayList<>();
    private List<String> mLeaveItems = new ArrayList<>();

    //1公路、2城市道路、3厂矿道路、4林区道路
    private String[] types = new String[]{"公路", "城市道路", "厂矿道路", "林区道路"};
    //1一级、2二级、3 三级、4四级
    private String[] leaves = new String[]{"一级", "二级", "三级", "四级"};

    /**
     * 采集位置集合
     */
    private String locListStr;

    @Override
    protected int setView() {
        return R.layout.activity_collection_road_others;
    }

    @Override
    protected void receiveData() {
        //接收参数
        Intent intent = getIntent();
        locListStr = intent.getStringExtra("locListStr");
        Log.i(TAG, "获取采集位置集合：" + locListStr);
    }

    @Override
    protected void initializeView() {

        //初始化采集时间
        createTimeTv.setText(DateUtil.dateToStr(DateUtil.DATE_FORMAT_MM_SS));

        mTypeItems.clear();
        mTypeItems.addAll(Arrays.asList(types));

        mLeaveItems.clear();
        mLeaveItems.addAll(Arrays.asList(leaves));

        clicks();


    }

    private void clicks() {
        RxView.clicks(backIv).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            finish();
        });

        RxView.clicks(rightIv).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            if (Utils.isLoginOffLine(getApplicationContext())){
                return;
            }
            Intent intentList = new Intent(CollectionRoadOthersActivity.this, CollectionListActivity.class);
            intentList.putExtra("type", 0);
            startActivity(intentList);
        });

        //保存
        RxView.clicks(bnSave).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            roadInfoSave();
        });

        //选择道路级别
        RxView.clicks(llRoadLeave).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            AndroidUtil.closeInputMethod(context, etRoadName);
            loadLeave();
        });

        //选择道路类型
        RxView.clicks(llRoadType).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            AndroidUtil.closeInputMethod(context, etRoadName);
            loadType();
        });
    }

    /**
     * 道路信息采集保存
     */
    private void roadInfoSave() {

        String roadName = etRoadName.getText().toString().trim();
        if (StringUtil.isBlank(roadName)) {
            ToastUtils.show("道路名称不能为空");
            return;
        }

        String roadType = tvRoadType.getText().toString().trim();
        if (StringUtil.isBlank(roadType)) {
            ToastUtils.show("请先选择道路类型");
            return;
        }

        String roadLeave = tvRoadLeave.getText().toString().trim();
        if (StringUtil.isBlank(roadLeave)) {
            ToastUtils.show("请先选择道路级别");
            return;
        }

        String roadRemark = etRemark.getText().toString().trim();

        Map<String, Object> maps = new HashMap<>();
        maps.put("userid", drUid);
        maps.put("token", token);
        maps.put("roadName", roadName);//道路名称
        String type = roadTypeStr(roadType);
        maps.put("roadType", type);//道路类型
        String leave = roadLeaveStr(roadLeave);
        maps.put("roadLeave", leave);//道路级别
        maps.put("remark", roadRemark);//备注
        maps.put("locationSet", locListStr);//位置集合

        // 这里应该有判断，是离线还是非离线，；离线保存数据库，非离线，上传
        //isOnLine 0离线 1非离线
        int isOnLine = PrefsUtil.getInt(context, CommonKey.ISONLINE);
        if (isOnLine == 0) {
            //保存数据库
            CollectionRoadModel collectionRoadModel = new CollectionRoadModel();
            collectionRoadModel.setCreateTime(System.currentTimeMillis() + "");
            collectionRoadModel.setRoadName(roadName);
            collectionRoadModel.setRoadType(type);
            collectionRoadModel.setRoadLeave(leave);
            collectionRoadModel.setRemark(roadRemark);
            collectionRoadModel.setLocationSet(locListStr);
            //type 1道路采集 2巡护采集 3资源 4火场  5小班
            collectionRoadModel.setType(1);
            //保存操作
            collectionRoadModel.save();
            if (collectionRoadModel.save()) {
                ToastUtils.show("保存成功");
                finish();
            } else {
                ToastUtils.show("保存失败");
            }
        } else {
            showPd();
            presenter.roadInformationInsert(maps);
        }
    }

    /**
     * 道路类型
     *
     * @param type
     * @return
     */
    private String roadTypeStr(String type) {
        String types = "";
        if (type.equals("公路")) {
            types = "1";
        }

        if (type.equals("城市道路")) {
            types = "2";
        }

        if (type.equals("厂矿道路")) {
            types = "3";
        }

        if (type.equals("林区道路")) {
            types = "4";
        }

        return types;
    }

    /**
     * 道路类型
     *
     * @param type
     * @return
     */
    private String roadLeaveStr(String type) {
        String types = "";
        if (type.equals("一级")) {
            types = "1";
        }

        if (type.equals("二级")) {
            types = "2";
        }

        if (type.equals("三级")) {
            types = "3";
        }

        if (type.equals("四级")) {
            types = "4";
        }

        return types;
    }

    @Override
    protected void loadDataFromServer() {

    }

    @Override
    public void onSuccess(Object model, int tag, String msg) {
        switch (tag) {
            case ResponseTag.ROAD_INFO_COLLECTION:
                CollectionRoadModel collectionRoadModel = (CollectionRoadModel) model;
                if (null != collectionRoadModel) {
                    ToastUtils.show(msg == null ? "保存成功" : msg);
                    //保存成功后，跳转列表
                    Intent intentList0 = new Intent(CollectionRoadOthersActivity.this, CollectionListActivity.class);
                    intentList0.putExtra("type", 0);
                    startActivity(intentList0);

                    finish();
                }
                break;

            default:
                break;
        }

        hidePd();
    }

    @Override
    public void onError(int errcode, int tag, String message) {
        hidePd();
        ToastUtils.show(message == null ? "保存失败" : message);
    }


    private OptionsPickerView pvTypeOptions;

    private int mTypePosition;

    private void loadType() {
        // 注意：自定义布局中，id 为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针
        // 具体可参考 demo 里面的两个自定义布局
        pvTypeOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = mTypeItems.get(options1);
                mTypePosition = options1;
                tvRoadType.setText(tx);
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        //自定义布局中的控件初始化及事件处理
                        TextView tv_finish = v.findViewById(R.id.tv_finish);
                        TextView titleTv = v.findViewById(R.id.titleTv);
                        titleTv.setText("选择道路类型");
                        tv_finish.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvTypeOptions.returnData();
                                pvTypeOptions.dismiss();
                            }
                        });

                        TextView tv_cancel = v.findViewById(R.id.tv_cancel);
                        tv_cancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvTypeOptions.dismiss();
                            }
                        });
                    }
                })
                .build();
        pvTypeOptions.setPicker(mTypeItems);//添加数据
        pvTypeOptions.show();
    }

    private OptionsPickerView pvLeaveOptions;

    private int mLeavePosition;

    private void loadLeave() {
        // 注意：自定义布局中，id 为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针
        // 具体可参考 demo 里面的两个自定义布局
        pvLeaveOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = mLeaveItems.get(options1);
                mLeavePosition = options1;
                tvRoadLeave.setText(tx);
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        //自定义布局中的控件初始化及事件处理
                        TextView tv_finish = v.findViewById(R.id.tv_finish);
                        TextView titleTv = v.findViewById(R.id.titleTv);
                        titleTv.setText("选择道路级别");
                        tv_finish.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvLeaveOptions.returnData();
                                pvLeaveOptions.dismiss();
                            }
                        });

                        TextView tv_cancel = v.findViewById(R.id.tv_cancel);
                        tv_cancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvLeaveOptions.dismiss();
                            }
                        });
                    }
                })
                .build();
        pvLeaveOptions.setPicker(mLeaveItems);//添加数据
        pvLeaveOptions.show();
    }
}
